package com.study.ju.service.redissontest.impl;

import com.study.ju.entity.Book;
import com.study.ju.entity.Books;
import com.study.ju.service.redissontest.RedissonServcie;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 陈涛
 * @description:
 * @Date 2019/6/26 13:43
 */
@Service
public class RedissonServcieImpl implements RedissonServcie {
    @Autowired
    private RedissonClient redissonClient;
    int mm=103;
    @Override
    public int testLock(int req) {
        RLock lock = redissonClient.getLock("anyLock");
        try {
            // 1. 最常见的使用方法
            lock.lock(10, TimeUnit.SECONDS);
            if(mm>0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+ "this is " + mm--);
            }
            lock.unlock();
        } catch (Exception e) {
            System.out.println("第一个异常");
            e.printStackTrace();
        } finally {
            try {
                //lock.unlock();
            }catch (Exception e){
                System.out.println("第二个异常");
                e.printStackTrace();
            }

        }

        return mm;
    }

    @Override
    public void testRedisson() {
        try {
            String s = redissonClient.getConfig().toJSON().toString();
            System.out.println(s);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    public int testNoLock() {
     /*   while(mm>0){
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "this is " + mm--);
        }*/
       // System.out.println("testNoLock");
        if(mm>0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+ "this is " + mm--);
        }
      /*  book.subtractionNum();
        return book.getNum();*/
      return mm;
    }
}
